package com.big.spike.config;

import com.big.common.utils.RedisScript;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class LuaLockConfiguration {

    /**
     * 向RedisScript塞入对应的Script
     * @return
     */
    @Bean
    public RedisScript redisScript() {
        RedisScript scripts = RedisScript.getInstance();
        //加锁
        DefaultRedisScript<Boolean> lockScript = new DefaultRedisScript<>();
        lockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/lock.lua")));
        lockScript.setResultType(Boolean.class);
        scripts.setLockScript(lockScript);
        //释放锁
        DefaultRedisScript<Boolean> unlockScript = new DefaultRedisScript<>();
        unlockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/unlock.lua")));
        unlockScript.setResultType(Boolean.class);
        scripts.setUnlockScript(unlockScript);
        //库存扣减
        DefaultRedisScript<Long> decrStockScript = new DefaultRedisScript<>();
        decrStockScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/decr_stock.lua")));
        decrStockScript.setResultType(Long.class);
        scripts.setDecrStockScript(decrStockScript);

        //查看是否秒杀过此商品
        DefaultRedisScript<Long> decrPatientScript = new DefaultRedisScript<>();
        decrPatientScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/patient.lua")));
        decrPatientScript.setResultType(Long.class);
        scripts.setDecrPatientScript(decrPatientScript);

        //添加秒杀记录
        DefaultRedisScript<Boolean> decrRecording = new DefaultRedisScript<>();
        decrRecording.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/recording.lua")));
        decrRecording.setResultType(Boolean.class);
        scripts.setDecrRecording(decrRecording);

        //查看商品库存
        DefaultRedisScript<Long> showStock = new DefaultRedisScript<>();
        showStock.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/show_stock.lua")));
        showStock.setResultType(Long.class);
        scripts.setShowStock(showStock);

        //秒杀提醒
        DefaultRedisScript<Boolean>  remindMe= new DefaultRedisScript<>();
        remindMe.setScriptSource(new ResourceScriptSource(new ClassPathResource("script/remind_me.lua")));
        remindMe.setResultType(Boolean.class);
        scripts.setRemindMe(remindMe);

        return scripts;
    }

}
